package cn.itcast.service.system.impl;

import cn.hutool.core.util.IdUtil;
import cn.itcast.dao.system.UserDao;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public List<User> findAll(String companyId) {
        return userDao.findAll(companyId);
    }

    @Override
    public User findById(String id) {
        return userDao.findById(id);
    }

    @Override
    public void save(User user) {
        user.setId(IdUtil.simpleUUID());
        userDao.save(user);
    }

    @Override
    public void update(User user) {
        userDao.update(user);
    }

    @Override
    public void delete(String id) {
        userDao.delete(id);
    }

    @Override
    public PageInfo findByPage(Integer pageNum, Integer pageSize, String companyId) {
        // 1.开启分页插件
        PageHelper.startPage(pageNum, pageSize);
        // 2.查询所有
        List<User> list = userDao.findAll(companyId);
        // 3.封装分页对象
        return new PageInfo(list);
    }

    @Override
    public List<String> findRoleIdListByUserId(String id) {

        return userDao.findRoleIdListByUserId(id);
    }

    @Override
    public void changeRole(String userId, String[] roleIds) {
        // 1.先根据用户id删除中间表数据
        userDao.deleteRoleIdsByUserId(userId);

        // 2.遍历角色数组，重新插入中间表数据
        if(roleIds!=null && roleIds.length>0){
            for (String roleId : roleIds) {
                userDao.saveRoleIdAndUserId(userId,roleId);
            }
        }
    }

    @Override
    public User findByEmail(String email) {
        return userDao.findByEmail(email);
    }
}
